package com.examsystem.service.impl;


import com.examsystem.dao.MenuMapper;
import com.examsystem.dao.UserMapper;
import com.examsystem.pojo.vo.LoginUser;
import com.examsystem.pojo.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author fire'ge
 */
@Service("userDetailServiceImpl")
public class UserDetailServiceImpl implements UserDetailsService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private MenuMapper menuMapper;

    public UserDetailServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String phoneNum) throws UsernameNotFoundException {

        User user = userMapper.queryUserByUsername(phoneNum);
        if(Objects.isNull(user)) {
            throw new RuntimeException("用户名或者密码错误");
        }
        List<String> list = menuMapper.queryPermsByUserId(user.getUserId());
        return new LoginUser(user,list);
    }



    public UserDetails loadUserByUsername(String phoneNum,String password) throws UsernameNotFoundException {
        User user = userMapper.findUserByPhonePwd(phoneNum,password);
        if(Objects.isNull(user)) {
            throw new RuntimeException("用户名或者密码错误");
        }
        List<String> list = menuMapper.queryPermsByUserId(user.getUserId());
        return new LoginUser(user,list);
    }
}
